<template>
  <uni-popup ref="popupRef" :is-mask-click="false">
    <view class="popup">
      <view class="cropper">
        <VueCropper
          ref="cropperRef"
          :img="newTempurl"
          :outputType="options.outputType"
          :autoCrop="options.autoCrop"
          :fixed="options.fixed"
          :fixedNumber="options.fixedNumber"
          :infoTrue="options.infoTrue"
          :full="options.full"
          :maxImgSize="maxImgSize"
          :fillColor="options.fillColor"
        />
      </view>
      <view class="function">
        <view
          @click="handleFunction(item)"
          class="function-item"
          v-for="item in functionList"
          :key="item.id"
        >
          <text :class="`iconfont ${item.icon}`" v-if="item.icon"></text>
          <text v-else>{{ item.text }}</text>
        </view>
      </view>
      <view class="operate-btn">
        <button type="primary" size="mini" @click="handleSave">保存</button>
        <button type="warn" size="mini" @click="cancel">取消</button>
      </view>
    </view>
  </uni-popup>
</template>

<script setup>
import { ref, nextTick,computed } from 'vue';
import 'vue-cropper/dist/index.css';
import { VueCropper } from 'vue-cropper';
import { useCropper } from './hooks';
const cropperRef = ref(null);

const { options,functionList ,handleFunction} = useCropper(cropperRef);
const props = defineProps({
  src: {
    type: String,
    default: '',
  },
  maxImgSize: {
    type: Number,
    default: 3000,
  },
});
const emit = defineEmits(['save']);
const popupRef = ref(null);
const newTempurl = computed(() => {
  return props.src.startsWith('http')
    ? props.src + '?t=' + Date.now()
    : props.src;
});
const open = () => {
  popupRef.value.open();
};
const close = () => {
  popupRef.value.close();
};

const handleSave = () => {
  cropperRef.value.getCropBlob((data) => {
    emit('save', URL.createObjectURL(data));
    close();
  });
};

const cancel = () => {
  close();
};

defineExpose({
  open,
  close,
});
</script>

<style lang="scss" scoped>
.popup {
  width: 500px;
  min-height: 300px;
  background-color: #fff;
  border-radius: 10px;
  padding: 20px;
  .cropper {
    width: 100%;
    aspect-ratio: 1 / 1;
  }
  .function {
    display: flex;
    gap: 10px;
    padding: 20px 0;
    .function-item {
      border: 1px solid #2979ff;
      color: #2979ff;
      padding: 5px 10px;
      font-size: 14px;
      cursor: pointer;
      user-select: none; // 禁止用户选择文本
    }
    .function-item:active {
      transform: scale(0.96);
    }
  }
}
</style>
